package com.mall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.entity.Permission;
import com.mall.entity.RolePermission;
import com.mall.user.mapper.RolePermissionMapper;
import com.mall.user.service.PermissionService;
import com.mall.user.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper permissionMapper;


    //根据用户id获取用户菜单
    @Override
    public List<String> selectPermissionValueByUsername(String username) {
        List<String> selectPermissionValueList = null;
        if ("admin".equals(username)) {
            //如果是系统管理员，获取所有权限
            selectPermissionValueList = permissionMapper.selectAllPermissionValue();
        } else {
            selectPermissionValueList = permissionMapper.selectPermissionValueByUsername(username);
        }
        return selectPermissionValueList;
    }

    @Override
    public List<Permission> getAllPermission() {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Permission::getType,2);
        List<Permission> permissionList = permissionMapper.selectList(queryWrapper);
        return permissionList;
    }

    /**
     * 查询菜单权限
     * @return
     */
    @Override
    public List<Permission> slectPermissionMenu() {
        QueryWrapper<Permission> wrapper = new QueryWrapper();
        wrapper.lambda().eq(Permission::getPid,1);
        List<Permission> permissionList = permissionMapper.selectList(wrapper);
        return permissionList;
    }

    @Override
    public List<Permission> slectPermissionByMenuId(Integer menuId, Integer roleId) {
        //查询该角色拥有的权限
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.lambda().select(RolePermission::getPermissionId).eq(RolePermission::getRoleId,roleId);
        List<RolePermission> rolePermissionList = rolePermissionMapper.selectList(rolePermissionQueryWrapper);
        ArrayList<Integer> permissionIdList = new ArrayList<>();
        for (RolePermission rolePermission : rolePermissionList) {
            permissionIdList.add(rolePermission.getPermissionId());
        }
        //查询该菜单下角色没有的权限
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Permission::getType,2).eq(Permission::getPid,menuId);
        if (permissionIdList.size() != 0) {
            queryWrapper.lambda().notIn(Permission::getId,permissionIdList);
        }
        List<Permission> permissionList = permissionMapper.selectList(queryWrapper);
        return permissionList;
    }


}


